package com.tmt.im.manager.service;

import com.tmt.data.jpa.service.IDataInitializer;
import com.tmt.im.manager.IMManagerApplication;
import com.tmt.springboot.common.helper.PackageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/7/30 16:51
 * @Version 1.0
 **/
@Slf4j
@Service
public class Initializer {

    @Async("asyncTaskExecutor")
    public void initialize(ApplicationContext context, Class<?> mainClass) {
        try {
            Object application = context.getBean(mainClass);
            List<Class<?>> serviceClasses = PackageHelper.findAllClassByAnnotation(application.getClass().getPackageName(),
                    Service.class, -1);
            try {
                serviceClasses.stream()
                        .filter(x -> IDataInitializer.class.isAssignableFrom(x) && x.getAnnotation(Order.class) != null)
                        .sorted(Comparator.comparingInt((x) -> x.getAnnotation(Order.class).value()))
                        .forEach(x -> {
                            IDataInitializer initializer = (IDataInitializer) context.getBean(x);
                            initializer.InitializeTable();
                        });
            } catch (Exception ex) {
                log.debug(ex.getMessage(), ex);
            }
        } catch (Exception ex) {
            log.error("----------Initializer.initialize()---------{}", mainClass.getSimpleName());
        }
    }

}
